<!-- eslint-disable vue/no-deprecated-slot-attribute -->
<!-- eslint-disable vue/no-deprecated-slot-scope-attribute -->
<!-- eslint-disable vue/no-deprecated-v-bind-sync -->
<!-- eslint-disable no-unused-vars -->
<template>
  <div class="order-management-container">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/dealer' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>订单管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 订单列表 -->
    <el-card class="content-card">
      <div slot="header" class="card-header">
        <span>订单列表</span>
        <el-button type="primary" size="small" @click="openAddDialog" style="margin-right: 500px">创建订单</el-button>
      </div>

      <!-- 搜索区域 -->
<!--      <el-row :gutter="20" class="search-area">-->
<!--        <el-col :span="6">-->
<!--          <el-input placeholder="请输入订单号" v-model="queryParams.orderNumber" clearable>-->
<!--            <el-button slot="append" icon="el-icon-search" @click.prevent="searchOrder($event)"></el-button>-->
<!--          </el-input>-->
<!--        </el-col>-->
<!--        <el-col :span="6">-->
<!--          <el-input placeholder="请输入产品名称" v-model="queryParams.productName" clearable>-->
<!--            <el-button slot="append" icon="el-icon-search" @click.prevent="searchOrder($event)"></el-button>-->
<!--          </el-input>-->
<!--        </el-col>-->
<!--        <el-col :span="6">-->
<!--          <el-select v-model="queryParams.orderStatus" placeholder="订单状态" clearable style="width: 100%">-->
<!--            <el-option label="待支付" value="待支付"></el-option>-->
<!--            <el-option label="已支付" value="已支付"></el-option>-->
<!--            <el-option label="待发货" value="待发货"></el-option>-->
<!--            <el-option label="已发货" value="已发货"></el-option>-->
<!--            <el-option label="已完成" value="已完成"></el-option>-->
<!--            <el-option label="已取消" value="已取消"></el-option>-->
<!--          </el-select>-->
<!--        </el-col>-->
<!--        <el-col :span="6">-->
<!--          <el-date-picker-->
<!--            v-model="queryParams.dateRange"-->
<!--            type="daterange"-->
<!--            range-separator="至"-->
<!--            start-placeholder="开始日期"-->
<!--            end-placeholder="结束日期"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            style="width: 100%;">-->
<!--          </el-date-picker>-->
<!--        </el-col>-->
<!--      </el-row>-->

<!--      <el-row :gutter="20" class="search-area">-->
<!--        <el-col :span="6">-->
<!--          <el-button type="primary" @click.prevent="searchOrder($event)">搜索</el-button>-->
<!--          <el-button @click.prevent="resetQuery($event)">重置</el-button>-->
<!--        </el-col>-->
<!--      </el-row>-->

      <!-- 表格 -->
      <safe-resize-wrapper identifier="order-table">
        <el-table :data="orderList" border stripe style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column prop="orderNumber" label="订单号" width="120"></el-table-column>
        <el-table-column prop="productName" label="产品名称" width="120"></el-table-column>
        <el-table-column prop="quantity" label="数量" width="80"></el-table-column>
        <el-table-column prop="totalAmount" label="总金额" width="120">
          <template v-slot="scope">
            ¥{{ scope.row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="客户名称" width="120"></el-table-column>
        <el-table-column prop="customerPhone" label="联系电话" width="120"></el-table-column>
          <el-table-column prop="location" label="商家地址" width="120"></el-table-column>
          <el-table-column prop="sales" label="自销/经销" width="120"></el-table-column>



          <!--        <el-table-column prop="orderTime" label="下单时间" width="160"></el-table-column>-->
<!--        <el-table-column prop="orderStatus" label="订单状态" width="100">-->
<!--          <template v-slot="scope">-->
<!--            <el-tag :type="getOrderStatusType(scope.row.orderStatus)">{{ scope.row.orderStatus }}</el-tag>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column label="操作" width="260">-->
<!--          <template v-slot="scope">-->
<!--              <el-button type="primary" size="mini" icon="el-icon-view" @click.prevent="handleView(scope.row)">详情</el-button>-->
<!--              <el-button type="warning" size="mini" icon="el-icon-edit" @click.prevent="handleEdit(scope.row, $event)" v-if="scope.row.orderStatus === '待支付'">编辑</el-button>-->
<!--              <el-button type="success" size="mini" icon="el-icon-money" @click.prevent="handlePay(scope.row)" v-if="scope.row.orderStatus === '待支付'">支付</el-button>-->
<!--              <el-button type="info" size="mini" icon="el-icon-position" @click.prevent="handleShip(scope.row)" v-if="scope.row.orderStatus === '待发货' || scope.row.orderStatus === 'PAID'">-->
<!--                发货-->
<!--                <span style="display: none;">{{ console.log('发货按钮状态:', scope.row.orderStatus) }}</span>-->
<!--              </el-button>-->
<!--              <el-button type="danger" size="mini" icon="el-icon-close" @click.prevent="handleCancel(scope.row)" v-if="scope.row.orderStatus === '待支付' || scope.row.orderStatus === 'PENDING'">-->
<!--                取消-->
<!--                <span style="display: none;">{{ console.log('取消按钮状态:', scope.row.orderStatus) }}</span>-->
<!--              </el-button>-->
<!--          </template>-->
<!--        </el-table-column>-->
          <template v-slot:empty>
            <div class="empty-text">
              <p>暂无订单数据</p>
              <el-button type="primary" size="small" @click="getOrderList">刷新</el-button>
            </div>
          </template>
      </el-table>
      </safe-resize-wrapper>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 订单详情对话框 -->
    <safe-resize-wrapper identifier="order-details-dialog">
      <el-dialog title="订单详情" v-model="detailDialogVisible" width="60%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">{{ currentOrder.orderNumber }}</el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ currentOrder.orderTime }}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{ currentOrder.productName }}</el-descriptions-item>
        <el-descriptions-item label="产品编码">{{ currentOrder.productCode }}</el-descriptions-item>
        <el-descriptions-item label="产品批次">{{ currentOrder.batchNumber }}</el-descriptions-item>
        <el-descriptions-item label="产品单价">¥{{ currentOrder.unitPrice ? currentOrder.unitPrice.toFixed(2) : '0.00' }}</el-descriptions-item>
        <el-descriptions-item label="购买数量">{{ currentOrder.quantity }}</el-descriptions-item>
        <el-descriptions-item label="总金额">¥{{ currentOrder.totalAmount ? currentOrder.totalAmount.toFixed(2) : '0.00' }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ currentOrder.customerName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentOrder.customerPhone }}</el-descriptions-item>
        <el-descriptions-item label="收货地址" :span="2">{{ currentOrder.deliveryAddress }}</el-descriptions-item>
<!--        <el-descriptions-item label="订单状态">-->
<!--          <el-tag :type="getOrderStatusType(currentOrder.orderStatus)">{{ currentOrder.orderStatus }}</el-tag>-->
<!--        </el-descriptions-item>-->
        <el-descriptions-item label="支付方式" v-if="currentOrder.paymentMethod">{{ currentOrder.paymentMethod }}</el-descriptions-item>
        <el-descriptions-item label="支付时间" v-if="currentOrder.paymentTime">{{ currentOrder.paymentTime }}</el-descriptions-item>
        <el-descriptions-item label="物流单号" v-if="currentOrder.logisticsNumber">{{ currentOrder.logisticsNumber }}</el-descriptions-item>
        <el-descriptions-item label="物流公司" v-if="currentOrder.logisticsCompany">{{ currentOrder.logisticsCompany }}</el-descriptions-item>
        <el-descriptions-item label="备注信息" :span="2" v-if="currentOrder.remark">{{ currentOrder.remark }}</el-descriptions-item>
      </el-descriptions>

      <div slot="footer" class="dialog-footer">
          <el-button @click.prevent="detailDialogVisible = false">关 闭</el-button>
          <el-button type="primary" @click.prevent="printOrder($event)" v-if="currentOrder.orderStatus !== '待支付' && currentOrder.orderStatus !== '已取消'">打印订单</el-button>
      </div>
    </el-dialog>
    </safe-resize-wrapper>

    <!-- 创建/编辑订单对话框 -->
    <safe-resize-wrapper identifier="order-edit-dialog">
      <el-dialog :title="dialogTitle" v-model="dialogVisible" width="60%" @close="resetForm">
      <el-form :model="orderForm" :rules="orderRules" ref="orderFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品选择" prop="productId">
              <el-select v-model="orderForm.productId" placeholder="请选择产品" style="width: 100%" @change="handleProductChange">
                <el-option
                  v-for="item in productOptions"
                  :key="item.id"
                  :label="item.productName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="自销/经销" prop="productId">
              <el-select v-model="orderForm.sales" placeholder="请选择" style="width: 100%" @change="handleProductChange">
                <el-option
                    label="厂家自销"
                    value="厂家自销"> <!-- 这里的值可以是数字或字符串，根据你的业务需求 -->
                </el-option>
                <el-option
                    label="经销商"
                    value="经销商">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批次号" prop="batchNumber">
              <el-input v-model="orderForm.batchNumber" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商家地址" prop="batchNumber">
              <el-input v-model="orderForm.location"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单价(元)" prop="unitPrice">
              <el-input v-model.number="orderForm.unitPrice" placeholder="请输入单价" @change="calculateTotal"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="quantity">
              <el-input-number v-model="orderForm.quantity" :min="1" :max="1000" @change="calculateTotal"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="总金额(元)" prop="totalAmount">
              <el-input v-model="orderForm.totalAmount" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商家名称" prop="customerName">
              <el-input v-model="orderForm.customerName" placeholder="请输入商家名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="customerPhone">
              <el-input v-model="orderForm.customerPhone" placeholder="请输入联系电话"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收货地址" prop="deliveryAddress">
              <el-input v-model="orderForm.deliveryAddress" placeholder="请输入收货地址"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注信息" prop="remark">
          <el-input type="textarea" v-model="orderForm.remark" placeholder="请输入备注信息" :rows="3"></el-input>
        </el-form-item>
      </el-form>



      <div slot="footer" class="dialog-footer">
          <el-button @click.prevent="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click.prevent="submitForm($event)">确 定</el-button>
      </div>
    </el-dialog>
    </safe-resize-wrapper>

    <!-- 支付对话框 -->
    <safe-resize-wrapper identifier="payment-dialog">
      <el-dialog title="订单支付" v-model="payDialogVisible" width="40%">
      <el-form :model="payForm" :rules="payRules" ref="payFormRef" label-width="100px">
        <el-form-item label="订单号">
          <el-input v-model="payForm.orderNumber" disabled></el-input>
        </el-form-item>
        <el-form-item label="支付金额">
          <el-input v-model="payForm.amount" disabled>
            <template v-slot:prepend>¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-radio-group v-model="payForm.paymentMethod">
            <el-radio label="支付宝">支付宝</el-radio>
            <el-radio label="微信支付">微信支付</el-radio>
            <el-radio label="银行转账">银行转账</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="交易凭证" prop="paymentProof" v-if="payForm.paymentMethod === '银行转账'">
          <el-upload
            class="payment-uploader"
            action="/api/file/upload"
            :show-file-list="false"
            :on-success="handleProofSuccess"
            :before-upload="beforeProofUpload">
            <img v-if="payForm.paymentProof" :src="payForm.paymentProof" class="payment-image">
            <i v-else class="el-icon-plus payment-uploader-icon"></i>
          </el-upload>
          <div class="upload-tip">请上传支付凭证截图，大小不超过2MB</div>
        </el-form-item>
        <div v-else class="payment-qrcode">
          <img src="https://example.com/qrcode.png" alt="支付二维码">
          <div class="qrcode-tip">请使用{{ payForm.paymentMethod }}扫描上方二维码完成支付</div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
          <el-button @click.prevent="payDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click.prevent="submitPayment($event)">确认支付</el-button>
      </div>
    </el-dialog>
    </safe-resize-wrapper>
  </div>
</template>

<script>
import { orderAPI, productAPI, paymentAPI } from '@/api/api';
import axios from 'axios';

export default {
  name: 'OrderManagementView',
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNumber: '',
        productName: '',
        orderStatus: '',
        dateRange: []
      },
      // 总记录数
      total: 0,
      // 订单列表
      orderList: [],
      // 加载状态
      loading: false,
      // 订单详情对话框显示状态
      detailDialogVisible: false,
      // 当前选中的订单
      currentOrder: {},
      // 对话框显示状态
      dialogVisible: false,
      // 对话框标题
      dialogTitle: '创建订单',
      // 订单表单
      orderForm: {
        id: null,
        productId: '',
        productName: '',
        productCode: '',
        batchNumber: '',
        unitPrice: 0,
        quantity: 1,
        totalAmount: '',
        customerName: '',
        customerPhone: '',
        deliveryAddress: '',
        remark: '',
        location:'',
        sales:'',
      },
      // 订单表单校验规则
      orderRules: {
        productId: [
          { required: true, message: '请选择产品', trigger: 'change' }
        ],
        unitPrice: [
          { required: true, message: '请输入单价', trigger: 'blur' },
          { validator: (rule, value, callback) => {
              if (value === '' || value === null || value === undefined) {
                callback(new Error('请输入单价'));
              } else if (isNaN(Number(value))) {
                callback(new Error('单价必须为数字'));
              } else if (Number(value) <= 0) {
                callback(new Error('单价必须大于0'));
              } else {
                callback();
              }
            }, trigger: 'blur' 
          }
        ],
        quantity: [
          { required: true, message: '请输入数量', trigger: 'change' },
          { validator: (rule, value, callback) => {
              if (value === '' || value === null || value === undefined) {
                callback(new Error('请输入数量'));
              } else if (isNaN(Number(value))) {
                callback(new Error('数量必须为数字'));
              } else if (Number(value) <= 0) {
                callback(new Error('数量必须大于0'));
              } else {
                callback();
              }
            }, trigger: 'change' 
          }
        ],
        customerName: [
          { required: true, message: '请输入客户名称', trigger: 'blur' }
        ],
        customerPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        deliveryAddress: [
          { required: true, message: '请输入收货地址', trigger: 'blur' }
        ]
      },
      // 产品选项
      productOptions: [],
      // 支付对话框显示状态
      payDialogVisible: false,
      // 支付表单
      payForm: {
        orderId: null,
        orderNumber: '',
        amount: '',
        paymentMethod: '银行转账',
        paymentProof: ''
      },
      // 支付表单校验规则
      payRules: {
        paymentMethod: [
          { required: true, message: '请选择支付方式', trigger: 'change' }
        ],
        paymentProof: [
          { required: true, message: '请上传交易凭证', trigger: 'change' }
        ]
      },
      // 添加防抖标志
      resizeObserverTimeout: null
    }
  },
  created() {
    console.log('OrderManagement组件创建');
    this.initializeComponent();
  },
  mounted() {
    // Add error handling for ResizeObserver, but don't block other events
    window.addEventListener('error', this.handleResizeObserverError, { passive: true });
    
    // Reset any previous patches to avoid conflicts
    if (this._originalObserve) {
      window.ResizeObserver.prototype.observe = this._originalObserve;
    }
  },
  beforeUnmount() {
    // Remove event listener
    window.removeEventListener('error', this.handleResizeObserverError);
  },
  methods: {
    // 初始化组件
    async initializeComponent() {
      try {
        console.log('初始化组件，加载数据');
        this.loading = true;
        await Promise.all([
          this.getOrderList(),
          this.getProductOptions()
        ]);
        console.log('组件初始化完成');
      } catch (error) {
        console.error('组件初始化失败:', error);
        this.$message.error('加载数据失败，请刷新页面重试');
      } finally {
        this.loading = false;
      }
    },
    // 获取订单列表
    async getOrderList() {
      try {
        console.log('开始获取订单列表, 查询参数:', this.queryParams);
        const response = await orderAPI.getOrders(this.queryParams);
        console.log('订单API响应:', response);
        if (response.success) {
          // 获取订单列表并处理订单状态
          let orders = response.data.content || [];
          
          // 打印第一个订单的完整数据结构以便调试
          if (orders.length > 0) {
            console.log('第一个订单数据示例:', JSON.stringify(orders[0]));
          }
          
          // 确保将英文状态转换为中文显示
          this.orderList = orders.map(order => {
            // 处理状态转换
            if (order.status && !order.orderStatus) {
              // 如果只有status字段而没有orderStatus字段
              order.orderStatus = this.mapOrderStatusToChinese(order.status);
            } else if (order.statusDisplay && !order.orderStatus) {
              // 如果有statusDisplay字段
              order.orderStatus = order.statusDisplay;
            } else if (!order.orderStatus) {
              // 兜底逻辑，如果orderStatus不存在，设置一个默认值
              order.orderStatus = '待处理';
            }
            console.log(`订单 ${order.orderNumber || order.id} 的状态: ${order.status} -> ${order.orderStatus}`);
            return order;
          });
          
          this.total = response.data.totalElements || 0;
          console.log('获取到的订单数据:', this.orderList);
          console.log('订单总数:', this.total);
        } else {
          console.warn('获取订单API返回失败状态:', response.message);
        }
      } catch (error) {
        console.error('获取订单列表失败:', error);
        this.$message.error('获取订单列表失败: ' + (error.message || '未知错误'));
        this.orderList = [];
        this.total = 0;
      }
    },
    // 将订单状态枚举映射为中文显示
    mapOrderStatusToChinese(status) {
      const statusMap = {
        'PENDING': '待支付',
        'PAID': '待发货',
        'SHIPPED': '已发货',
        'DELIVERED': '已送达',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消'
      };
      return statusMap[status] || status;
    },
    // 获取产品选项
    async getProductOptions() {
      try {
        console.log('开始获取产品选项...');
        const response = await productAPI.getProducts();
        console.log('产品API响应:', response);
        
        if (response.success && response.data) {
          // 检查响应结构
          if (response.data.content) {
            this.productOptions = response.data.content;
            console.log('获取到产品选项:', this.productOptions);
          } else if (Array.isArray(response.data)) {
            // 直接是数组的情况
            this.productOptions = response.data;
            console.log('获取到产品选项(数组):', this.productOptions);
          } else {
            // 其他情况
            this.productOptions = [];
            console.warn('产品数据格式不符合预期:', response.data);
          }
          
          // 调试：打印每个产品项的ID格式
          if (this.productOptions.length > 0) {
            console.log('产品选项的第一项:', this.productOptions[0]);
            console.log('产品ID的类型:', typeof this.productOptions[0].id);
          }
        } else {
          console.warn('API返回错误或数据为空:', response);
          this.$message.error('获取产品选项失败: ' + (response.message || '未知错误'));
          this.productOptions = [];
        }
      } catch (error) {
        console.error('获取产品选项失败:', error);
        this.$message.error('获取产品选项失败: ' + (error.message || '未知错误'));
        this.productOptions = [];
      }
    },
    // 获取订单状态对应的类型
    getOrderStatusType(status) {
      switch (status) {
        case '待支付':
          return 'info'
        case '已支付':
          return 'warning'
        case '待发货':
          return 'primary'
        case '已发货':
          return 'success'
        case '已完成':
          return 'success'
        case '已取消':
          return 'danger'
        default:
          return 'info'
      }
    },
    // 搜索订单
    searchOrder(event) {
      if (event) {
        event.preventDefault();
      }
      this.queryParams.pageNum = 1;
      this.getOrderList();
    },
    // 重置查询
    resetQuery(event) {
      if (event) {
        event.preventDefault();
      }
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        orderNumber: '',
        productName: '',
        orderStatus: '',
        dateRange: []
      };
      this.getOrderList();
    },
    // 处理每页数量变化
    handleSizeChange(val, event) {
      if (event) {
        event.preventDefault();
      }
      this.queryParams.pageSize = val;
      this.getOrderList();
    },
    // 处理页码变化
    handleCurrentChange(val, event) {
      if (event) {
        event.preventDefault();
      }
      this.queryParams.pageNum = val;
      this.getOrderList();
    },
    // 查看详情
    async handleView(row) {
      try {
        const response = await orderAPI.getOrderById(row.id);
        if (response.success) {
          this.currentOrder = response.data;
          this.detailDialogVisible = true;
        } else {
          this.$message.error('获取订单详情失败: ' + response.message);
        }
      } catch (error) {
        console.error('获取订单详情失败:', error);
        this.$message.error('获取订单详情失败: ' + (error.message || '未知错误'));
      }
    },
    // 打印订单
    async printOrder(event) {
      if (event) {
        event.preventDefault();
      }
      try {
        const response = await orderAPI.printOrder(this.currentOrder.id);
        if (response.success) {
          this.$message.success('订单已发送至打印队列');
        } else {
          this.$message.error('打印订单失败: ' + response.message);
        }
      } catch (error) {
        console.error('打印订单失败:', error);
        this.$message.error('打印订单失败: ' + (error.message || '未知错误'));
      }
    },
    // 打开创建对话框
    openAddDialog(event) {
      if (event) {
        event.preventDefault();
      }
      this.dialogTitle = '创建订单';
      this.resetForm(); // Reset form before showing
      this.dialogVisible = true;
      
      // Use requestAnimationFrame for smoother handling
      requestAnimationFrame(() => {
        if (this.$refs.orderFormRef) {
          this.$refs.orderFormRef.clearValidate();
        }
      });
    },
    // 处理产品变更
    handleProductChange(val) {
      console.log('产品变更，选中ID:', val, '类型:', typeof val);
      console.log(this.orderForm.sales)
      const product = this.productOptions.find(item => item.id === val);
      console.log('找到的产品对象:', product);
      
      if (product) {
        this.orderForm.productId = val; // 确保明确赋值
        this.orderForm.productName = product.productName;
        this.orderForm.productCode = product.productCode;
        this.orderForm.batchNumber = product.batchNumber;
        this.orderForm.unitPrice = Number(product.price) || 0;
        this.calculateTotal();
        
        console.log('更新后的orderForm:', JSON.stringify(this.orderForm));
      } else {
        console.warn('未找到产品，ID:', val);
      }
    },
    // 计算总金额
    calculateTotal() {
      if (this.orderForm.unitPrice && this.orderForm.quantity) {
        // 确保将字符串转换为数字进行计算
        const price = Number(this.orderForm.unitPrice);
        const quantity = Number(this.orderForm.quantity);
        this.orderForm.totalAmount = (price * quantity).toFixed(2);
      } else {
        this.orderForm.totalAmount = '0.00';
      }
    },
    // 处理编辑
    handleEdit(row, event) {
      if (event) {
        // Prevent any browser defaults but don't stop propagation
        event.preventDefault();
      }
      
      this.dialogTitle = '编辑订单';
      this.orderForm = JSON.parse(JSON.stringify({
        id: row.id,
        productId: this.productOptions.find(item => item.productCode === row.productCode)?.id || '',
        productName: row.productName,
        productCode: row.productCode,
        batchNumber: row.batchNumber,
        unitPrice: row.unitPrice,
        quantity: row.quantity,
        totalAmount: row.totalAmount.toFixed(2),
        customerName: row.customerName,
        customerPhone: row.customerPhone,
        deliveryAddress: row.deliveryAddress,
        remark: row.remark
      }));
      
      this.dialogVisible = true;
      
      // Use requestAnimationFrame for more reliable UI updates
      requestAnimationFrame(() => {
        if (this.$refs.orderFormRef) {
          this.$refs.orderFormRef.clearValidate();
        }
      });
    },
    // 处理支付
    async handlePay(row) {
      try {
        // 设置当前订单
        this.currentOrder = row;
        
        // 初始化支付表单
      this.payForm = {
        orderId: row.id,
        orderNumber: row.orderNumber,
        amount: row.totalAmount.toFixed(2),
          paymentMethod: '银行转账', // 默认选择银行转账
        paymentProof: ''
        };
        
        // 获取可用的支付方式
        try {
          const response = await paymentAPI.getPaymentMethods();
          if (response.success && response.data) {
            console.log('获取支付方式成功:', response.data);
            // 此处可以动态设置支付方式选项
          }
        } catch (apiError) {
          console.warn('获取支付方式失败，使用默认选项:', apiError);
        }
        
        // 显示支付对话框
        this.payDialogVisible = true;
        
        // 使用setTimeout代替debounce
        this.$nextTick(() => {
          clearTimeout(this.resizeObserverTimeout);
          this.resizeObserverTimeout = setTimeout(this.handleResize, 200);
        });
      } catch (error) {
        console.error('处理支付请求失败:', error);
        this.$message.error('处理支付请求失败: ' + (error.message || '未知错误'));
      }
    },
    // 处理发货
    async handleShip(row) {
      try {
        await this.$confirm('确认为该订单发货?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        // 如果用户点击了确定
        this.loading = true;
        console.log('调用发货API, ID:', row.id);
        
        // 实际场景中可以弹出发货信息录入对话框，此处简化为直接调用发货接口
        const logisticsData = {
          logisticsCompany: '顺丰快递',  // 这里应该是从表单中获取，现使用默认值
          trackingNumber: 'SF' + Date.now()  // 生成一个临时的跟踪号
        };
        
        console.log('发送的物流数据:', logisticsData);
        
        // 直接使用axios调用API，避免可能的封装问题
        try {
          const response = await axios.put(
            `http://localhost:8080/api/orders/${row.id}/ship`,
            logisticsData,
            { headers: { 'Content-Type': 'application/json' } }
          );
          
          console.log('发货API响应:', response);
          
          if (response.data && response.data.success) {
            this.$message.success('发货成功');
            await this.getOrderList();
          } else {
            this.$message.error('发货失败: ' + (response.data ? response.data.message : '未知错误'));
          }
        } catch (apiError) {
          console.error('发货API调用失败:', apiError.response || apiError);
          this.$message.error('发货API调用失败: ' + (apiError.response && apiError.response.data ? apiError.response.data.message : apiError.message));
        }
      } catch (error) {
        // 如果用户取消了确认对话框，这里会捕获到取消的错误
        if (error === 'cancel') {
          this.$message.info('已取消操作');
        } else {
          console.error('发货失败:', error);
          this.$message.error('发货失败: ' + (error.message || '未知错误'));
        }
      } finally {
        this.loading = false;
      }
    },
    // 处理取消
    async handleCancel(row) {
      try {
        await this.$confirm('确认取消该订单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
        });
        
        // 如果用户点击了确定
        this.loading = true;
        console.log('调用取消订单API, ID:', row.id);
        
        // 直接使用axios调用API，避免可能的封装问题
        try {
          const response = await axios.put(
            `http://localhost:8080/api/orders/${row.id}/cancel`,
            {},
            { headers: { 'Content-Type': 'application/json' } }
          );
          
          console.log('取消订单API响应:', response);
          
          if (response.data && response.data.success) {
            this.$message.success('订单已取消');
            await this.getOrderList(); // 刷新列表
          } else {
            this.$message.error('取消订单失败: ' + (response.data ? response.data.message : '未知错误'));
          }
        } catch (apiError) {
          console.error('取消订单API调用失败:', apiError.response || apiError);
          this.$message.error('取消订单API调用失败: ' + (apiError.response && apiError.response.data ? apiError.response.data.message : apiError.message));
        }
      } catch (error) {
        // 如果用户取消了确认对话框，这里会捕获到取消的错误
        if (error === 'cancel') {
          this.$message.info('已取消操作');
        } else {
          console.error('取消订单失败:', error);
          this.$message.error('取消订单失败: ' + (error.message || '未知错误'));
        }
      } finally {
        this.loading = false;
      }
    },
    // 提交表单
    async submitForm(event) {
      if (event) {
        event.preventDefault();
      }
      
      try {
        const valid = await this.$refs.orderFormRef.validate();
        
        if (valid) {
          // 额外验证产品ID
          if (!this.orderForm.productId) {
            this.$message.error('产品不能为空，请选择产品');
            return;
          }
          
          this.loading = true;
          
          // 获取当前用户信息，假设存储在localStorage中
          const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
          const dealerId = userInfo.id || 1; // 如果没有ID则使用默认值1
          
          // 打印完整的表单数据
          console.log('提交前的完整表单数据:', JSON.stringify(this.orderForm));
          
          // 生成订单号
          const orderNo = "ORD-" + Date.now().toString().substring(6) + Math.floor(Math.random() * 1000);
          
          // 确保product_id为数字且不为null
          const productId = parseInt(this.orderForm.productId, 10);
          
          if (isNaN(productId) || productId <= 0) {
            console.error('产品ID无效:', this.orderForm.productId);
            this.$message.error('产品ID无效，请重新选择产品');
            this.loading = false;
            return;
          }
          
          // 创建最简单的订单数据结构 - 使用单层结构避免嵌套
          const orderData = {
            orderNo: orderNo,
            productId: productId,
            dealerId: Number(dealerId),
            productName: this.orderForm.productName || '',
            batchNumber: this.orderForm.batchNumber || '',
            quantity: Number(this.orderForm.quantity) || 1,
            unitPrice: Number(this.orderForm.unitPrice) || 0,
            totalAmount: Number(this.orderForm.totalAmount) || 0,
            customerName: this.orderForm.customerName || '',
            customerPhone: this.orderForm.customerPhone || '',
            deliveryAddress: this.orderForm.deliveryAddress || '',
            remark: this.orderForm.remark || '',
            sales: this.orderForm.sales,
            location:this.orderForm.location,
            status: "PENDING"
          };
          
          console.log('准备提交的订单数据:', orderData);
          console.log('数据类型检查 - productId:', typeof orderData.productId, orderData.productId);
          
          if (this.orderForm.id !== null) {
            // 更新订单
            try {
              // 确保所有的字段类型正确
              const cleanedData = {
                id: this.orderForm.id,
                orderNo: orderData.orderNo,
                productId: Number(orderData.productId),  // 确保是数字
                dealerId: Number(orderData.dealerId),    // 确保是数字
                productName: orderData.productName || '',
                batchNumber: orderData.batchNumber || '',
                quantity: Number(orderData.quantity) || 1,
                unitPrice: Number(orderData.unitPrice) || 0,
                totalAmount: Number(orderData.totalAmount) || 0,
                customerName: orderData.customerName || '',
                customerPhone: orderData.customerPhone || '',
                deliveryAddress: orderData.deliveryAddress || '',
                remark: orderData.remark || '',
                status: orderData.status || "PENDING",
                location:orderData.location,
                sales:orderData.sales
              };

              console.log('发送更新订单的清理后数据:', JSON.stringify(cleanedData));
              
              const response = await axios.put(
                `http://localhost:8080/api/orders/${this.orderForm.id}`,
                cleanedData,
                { headers: { 'Content-Type': 'application/json' } }
              );
              
              console.log('更新订单响应:', response);
              
              if (response.data && response.data.success) {
                this.$message.success('订单修改成功');
                this.dialogVisible = false;
                await this.getOrderList();
          } else {
                this.$message.error('订单修改失败: ' + (response.data ? response.data.message : '未知错误'));
              }
            } catch (error) {
              console.error('更新订单请求失败:', error.response || error);
              if (error.response && error.response.data) {
                console.error('错误详情:', error.response.data);
              }
              this.$message.error('更新订单失败: ' + (error.response && error.response.data ? error.response.data.message : error.message));
            }
        } else {
            // 创建新订单
            try {
              // 由于后端期望的字段名可能与我们的前端字段名不同，确保按后端期望格式发送
              const backendData = {
                orderNo: orderData.orderNo,
                productId: orderData.productId,  // 这是关键字段，必须确保正确
                dealerId: orderData.dealerId,
                quantity: orderData.quantity,
                unitPrice: orderData.unitPrice,
                totalAmount: orderData.totalAmount,
                customerName: orderData.customerName,
                customerPhone: orderData.customerPhone,
                deliveryAddress: orderData.deliveryAddress,
                remark: orderData.remark,
                sales:orderData.sales,
                location: orderData.location,
                status: orderData.status
              };
              
              console.log('发送到后端的最终数据:', JSON.stringify(backendData));
              
              const response = await axios.post(
                'http://localhost:8080/api/orders', 
                backendData,
                { headers: { 'Content-Type': 'application/json' } }
              );
              
              console.log('创建订单响应:', response);
              
              if (response.data && response.data.success) {
                this.$message.success('订单创建成功');
                this.dialogVisible = false;
                await this.getOrderList();
              } else {
                this.$message.error('订单创建失败: ' + (response.data ? response.data.message : '未知错误'));
              }
            } catch (error) {
              console.error('创建订单请求失败:', error.response || error);
              if (error.response && error.response.data) {
                console.error('错误详情:', error.response.data);
              }
              this.$message.error('创建订单失败: ' + (error.response && error.response.data ? error.response.data.message : error.message));
            }
          }
        } else {
          console.warn('订单表单验证失败');
          return false;
        }
      } catch (error) {
        console.error('订单提交过程中出现异常:', error);
        this.$message.error('保存订单失败: ' + (error.message || '未知错误'));
      } finally {
        this.loading = false;
      }
    },
    // 重置表单
    resetForm() {
      if (this.$refs.orderFormRef) {
        this.$refs.orderFormRef.resetFields()
      }
      this.orderForm = {
        id: null,
        productId: '',
        productName: '',
        productCode: '',
        batchNumber: '',
        unitPrice: 0,
        quantity: 1,
        totalAmount: '',
        customerName: '',
        customerPhone: '',
        deliveryAddress: '',
        sales: '',
        remark: ''
      }
    },
    // 处理交易凭证上传成功
    handleProofSuccess(res) {
      if (res.success) {
        this.payForm.paymentProof = res.data.url; // 假设返回的是包含url的对象
      } else {
        this.$message.error('上传失败: ' + res.message);
        this.payForm.paymentProof = '';
      }
    },
    // 交易凭证上传前校验
    beforeProofUpload(file) {
      const isImage = file.type.indexOf('image/') === 0
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传图片只能是图片格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    },
    // 提交支付
    async submitPayment(event) {
      if (event) {
        event.preventDefault();
      }
      
      try {
        const valid = await this.$refs.payFormRef.validate();
        
        if (valid) {
          this.loading = true;
          
          const paymentData = {
            orderNumber: this.currentOrder.orderNumber,
            paymentMethod: this.payForm.paymentMethod,
            paymentProof: this.payForm.paymentProof,
            amount: this.payForm.amount
          };
          
          console.log('发送支付请求数据:', paymentData);
          // 使用新的支付API
          const response = await paymentAPI.processPayment(paymentData);
          
          if (response.success) {
            console.log('支付API调用成功:', response);
            this.$message.success('支付成功');
            this.payDialogVisible = false;
            await this.getOrderList();
        } else {
            console.error('支付API返回错误:', response);
            this.$message.error('支付失败: ' + response.message);
          }
        } else {
          console.warn('支付表单验证失败');
          return false;
        }
      } catch (error) {
        console.error('支付过程中出现异常:', error);
        this.$message.error('支付失败: ' + (error.message || '未知错误'));
      } finally {
        this.loading = false;
      }
    },
    // 处理resize的方法
    handleResize() {
      // 无需实际操作，只需确保resize事件被防抖处理
      console.log('Resize handled with timeout');
    },
    
    // 处理ResizeObserver错误
    handleResizeObserverError(event) {
      if (event && event.message && event.message.includes('ResizeObserver loop limit exceeded')) {
        console.warn('ResizeObserver error logged in component');
        // Don't stop propagation or prevent default - this can interfere with button clicks
        return false;
      }
      return false;
    }
  }
}
</script>

<style scoped>
.order-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
}

.payment-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.payment-uploader:hover {
  border-color: #409EFF;
}

.payment-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.payment-image {
  width: 178px;
  height: 178px;
  display: block;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

.payment-qrcode {
  text-align: center;
  margin: 20px 0;
}

.qrcode-tip {
  color: #606266;
  font-size: 14px;
  margin-top: 10px;
}

.empty-text {
  text-align: center;
  padding: 30px 0;
}

.empty-text p {
  margin-bottom: 15px;
  color: #909399;
}

/* 添加CSS解决方案，确保弹窗内容有最大高度限制，避免无限调整大小 */
.el-dialog__body {
  max-height: 70vh;
  overflow-y: auto;
}

/* 确保表格有固定高度，避免动态高度变化引起的无限循环 */
.el-table {
  height: auto !important;
  max-height: 70vh;
}

/* 添加全局样式覆盖，避免元素大小频繁计算 */
.el-table__body-wrapper, 
.el-table__header-wrapper {
  will-change: transform;
  transform: translateZ(0);
}
</style>
